const random = Math.random;
const floor = Math.floor;

export function last(arr) {
	return arr.slice(-1)[0];
}

export function lastIndex(arr) {
	return arr.length - 1;
}

/**
 * 随机整数
 * @param {number} n
 * @returns [0, n)
 */
export function intRand(n) {
	return floor(random() * n);
}

/**
 * 从范围[a, b)内随机
 * @param {number} a start
 * @param {number} b end
 * @returns [a, b)
 */
export function rand(a, b) {
	if (b) {
		const diff = b - a;
		return a + intRand(diff);
	}
	return intRand(a);
}

export function hexColor() {
	return (
		'#' +
		Array(6)
			.fill(0)
			.map(() => rand(16).toString(16))
			.join('')
	);
}

export function rgbColor() {
	return `rgb(${Array(3)
		.fill(0)
		.map(() => rand(256))
		.join(',')})`;
}

/**
 * 返回格式为`00:00`的时间
 * @param {Number} milliSeconds 毫秒时间
 * @returns {String} 00:00
 */
export const readableTime = (milliSeconds = 0) => {
	const hourTime = 60 * 60 * 1000;
	if (milliSeconds > hourTime) {
		return '-- : --';
	}

	const standard = new Date('2000-1-1 00:00:00');
	const relative = new Date(standard.getTime() + milliSeconds);
	const M = relative.getMinutes();
	const S = relative.getSeconds();

	return [M, S].map((t) => ('0' + t).slice(-2)).join(':');
};

export const throttle = function (func, delay) {
	let timer = null;
	return function (...args) {
		if (!timer) {
			timer = setTimeout(() => {
				func(...args);
				timer = null;
			}, delay);
		}
	};
};
